﻿using GCC.Container.Abstracts;
using GCC.Container.LogProviders;

namespace GCC.Container.PluginLoader
{
    /// <summary>
    /// 管理器
    /// </summary>
    public partial class Manager
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static readonly AbsGCCLogger _logger = GCCLoggerProvider.Instance!.CreateLogger<Manager>();
        /// <summary>
        /// 管理器实例
        /// </summary>
        public static readonly Manager Instance = new();
        /// <summary>
        /// 所有的插件实例
        /// </summary>
        public List<PluginInstance> AllPluginInstance { get => this._items; }

        /// <summary>
        /// DB初始化完毕
        /// </summary>
        public void DBInitiated(IDBManager db)
        {
            _logger.Trace("Start to invoke SetDBInstance method.");
            this._items.ForEach(item =>
            {
                try
                {
                    item.EnteranceInstance?.SetDBInstance(db);
                }
                catch (Exception ex)
                {
                    _logger.Error($"Call {item.Name}'s SetDBInstance error.", exception: ex);
                }
            });

            _logger.Trace("Invoke SetDBInstance method completed.");
        }
        /// <summary>
        /// 系统启动成功,异步通知.
        /// </summary>
        /// <param name="contex"></param>
        public void SystemStarted(AbsGCCContext contex)
        {
            _logger.Trace("Start to invoke OnSystemStarted method async.");
            var tasks = new List<Task>();
            this._items.ForEach(item =>
            {
                tasks.Add(Task.Run(() =>
                 {
                     try
                     {
                         item.EnteranceInstance?.OnSystemStarted(contex);
                     }
                     catch (Exception ex)
                     {
                         _logger.Error($"Call {item.Name}'s OnSystemStarted error.", exception: ex);
                     }
                 }));
            });
            Task.WaitAll(tasks.ToArray());
            _logger.Trace("Invoke OnSystemStarted method completed.");
        }

        /// <summary>
        /// 系统启动成功,同步通知,可以阻塞容器.
        /// </summary> 
        public void SystemStoping()
        {
            _logger.Trace("Start to invoke SystemTryShutDown method sync.");
            this._items.ForEach(item =>
            {
                try
                {
                    item.EnteranceInstance?.SystemTryShutDown();
                }
                catch (Exception ex)
                {
                    _logger.Error($"Call {item.Name}'s OnSystemStarted error.", exception: ex);
                }
            });
            _logger.Trace("Invoke SystemTryShutDown method completed.");
        }
    }
}
